package com.rockkang.gp.homework.designmode.singleton.register;

import com.rockkang.gp.homework.designmode.singleton.excepiton.BeanInvalidException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ContainerSingleton {
    private static final Map<String, Object> container = new ConcurrentHashMap<>();
    public static Object getBean(String clazzName) {
        if (container.containsKey(clazzName)) {
            return container.get(clazzName);
        }
        synchronized (Constructor.class) {
            if (container.containsKey(clazzName)) {
                return container.get(clazzName);
            }
            try {
                Class clazz = Class.forName(clazzName);
                return instanceBean(clazz);
            } catch (ClassNotFoundException e) {
//                e.printStackTrace();
                throw new BeanInvalidException(e);
            }
        }
    }

    private static Object instanceBean(Class clazz) {
        Object obj = null;
        try {
            try {

                Method method = clazz.getMethod("getInstance");
                obj = method.invoke(null);
            } catch (NoSuchMethodException e) {
//                    e.printStackTrace();
                // TODO 打印日志 message
            } catch (InvocationTargetException e) {
//                    e.printStackTrace();
                // TODO 打印日志 message
            }
            if (obj == null) {
                obj = clazz.newInstance();
            }
        } catch (InstantiationException e) {
//                e.printStackTrace();
            throw new BeanInvalidException(e);
        } catch (IllegalAccessException e) {
//                e.printStackTrace();
            throw new BeanInvalidException(e);
        }
        return obj;
    }
}
